﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using UCL;
using UCL.Data;
using UCL.Forms;

namespace DBKit5.UControls
{
    /// <summary>
    /// 数据库查询结果面板
    /// </summary>
    /// <remarks>2014-1-25 by sutroon</remarks>
    public partial class ucQueryResult : UserControl
    {
        /// <summary>
        /// 获取或设置数据库帮助类的实例对象
        /// </summary>
        public IDatabaseHelper DBH { get; set; }
        public ucQueryResult()
        {
            InitializeComponent();
            this.cmidgvClickConfig();
        }
        public void ExecuteSqls(params string[] sqls)
        {
            if (DBH == null)
            {
                MessageBox.Show("数据库未连接!");
                return;
            }
            this.Controls.Clear();
            if (AppDataHelper.APP_DEBUG) MessageBox.Show("当前执行的SQL:" + sqls.ToString(Environment.NewLine));
            List<Control> result = new List<Control>();
            DataGridView dgv;
            DataTable dt;
            int i = 0;
            foreach (string sql in sqls)
            {
                DBH.MessageSet.Clear();
                if (sql.Trim().ToLower().Substring(0, 4).IsIn("sele", "desc", "show"))
                {
                    dt = DBH.ExecuteDataTable(sql);
                    if (DBH.MessageSet.Count > 0)
                    {
                        result.Add(new Label() { Text = DBH.MessageSet.ToString(Environment.NewLine), Tag = sql });
                        continue;
                    }
                    dgv = new DataGridView() { Dock = DockStyle.Fill, Tag = sql, ContextMenuStrip = cmsDgv, DataSource = dt, AllowUserToAddRows = false, AllowUserToDeleteRows = false };
                    dgv.SetRowHeaderIndex(rowHeadersWidth: 50);
                    if (AppDataHelper.APP_DEBUG) MessageBox.Show("数据表格行数:" + dgv.Rows.Count);
                    result.Add(dgv);
                }
                else
                {
                    i = DBH.ExecuteNonQuery(sql);
                    result.Add(new Label() { Text = DBH.MessageSet.Count > 0 ? DBH.MessageSet.ToString(Environment.NewLine) : string.Format("执行成功,受影响行数{0}.", i), Tag = sql, AutoSize = true });
                }
            }
            if (AppDataHelper.APP_DEBUG) MessageBox.Show("查询结果面板数量:" + result.Count);
            AddPanels(result.ToArray());
        }
        public void AddPanels(params Control[] ctrls)
        {
            if (ctrls.Length == 0) return;
            if (ctrls.Length == 1)
            {
                this.Controls.Add(ctrls[0]);
                return;
            }
            SplitContainer sc = new SplitContainer() { Dock = DockStyle.Fill, Orientation = Orientation.Horizontal, SplitterWidth = 1, SplitterIncrement = 1, BorderStyle = BorderStyle.FixedSingle };
            sc.Panel1.Controls.Add(ctrls[0]);
            if (ctrls.Length == 2) sc.Panel2.Controls.Add(ctrls[1]);
            if (ctrls.Length > 2) AddPanelsFunc(ref sc, 2, ctrls);
            this.Controls.Add(sc);
        }
        private void AddPanelsFunc(ref SplitContainer sc, int count, Control[] ctrls)
        {
            if (count >= ctrls.Length) return;
            if (count == ctrls.Length - 1)
            {
                sc.Panel2.Controls.Add(ctrls[count]);
                return;
            }
            SplitContainer sct = new SplitContainer() { Dock = DockStyle.Fill, Orientation = Orientation.Horizontal, SplitterWidth = 1, SplitterIncrement = 1, BorderStyle = BorderStyle.FixedSingle };
            sct.Panel1.Controls.Add(ctrls[count]);
            count++;
            AddPanelsFunc(ref sct, count, ctrls);
            sc.Panel2.Controls.Add(sct);
        }

        private void cmidgvClickConfig()
        {
            cmidgv编辑命令ToolStripMenuItem.Click += new EventHandler(cmidgv_Click);
            cmidgv查看命令ToolStripMenuItem.Click += new EventHandler(cmidgv_Click);
            cmidgv导出数据ToolStripMenuItem.Click += new EventHandler(cmidgv_Click);
            cmidgv复制ToolStripMenuItem.Click += new EventHandler(cmidgv_Click);
            cmidgv属性AToolStripMenuItem.Click += new EventHandler(cmidgv_Click);
            cmidgv删除记录ToolStripMenuItem.Click += new EventHandler(cmidgv_Click);
            cmidgv刷新ToolStripMenuItem.Click += new EventHandler(cmidgv_Click);
            cmidgv新窗口显示ToolStripMenuItem.Click += new EventHandler(cmidgv_Click);
        }
        private void cmidgv_Click(object sender, EventArgs e)
        {
            ToolStripItem mi = (ToolStripItem)sender;
            DataGridView dgv = mi.GetSourceControl<DataGridView>();
            if (dgv == null) return;
            switch (mi.Name)
            {
                case "cmidgv编辑命令ToolStripMenuItem":
                    new frmEditSql() { SqlText = dgv.Tag.ToString(), Fields = dgv.GetColumnProperties(a => a.Name).ToString(", "), ExecuteSqlHandler = ExecuteSqlEvent, Tag = dgv }.Show();
                    break;
                case "cmidgv查看命令ToolStripMenuItem":
                    new frmEditSql() { SqlText = dgv.Tag.ToString() }.Show();
                    break;
                case "cmidgv导出数据ToolStripMenuItem":
                    string fn;
                    if (dgv.SaveAsExcel(out fn)) MessageBoxHelper.ConfirmOpenFolder(fn, "导出成功,是否打开文件所在的目录?");
                    break;
                case "cmidgv复制ToolStripMenuItem":
                    if (dgv.CurrentCell == null || dgv.CurrentCell.Value == DBNull.Value) return;
                    Clipboard.SetText(dgv.CurrentCell.Value.ToString());
                    break;
                case "cmidgv属性AToolStripMenuItem":
                    MessageBox.Show(string.Format("行数:{0}, 列数:{1}{2}{2}命令:{2}{3}", dgv.RowCount, dgv.ColumnCount, Environment.NewLine, dgv.Tag), "属性");
                    break;
                case "cmidgv删除记录ToolStripMenuItem":
                    if (dgv.CurrentCell == null) return;
                    StringBuilder sb = new StringBuilder();
                    foreach (DataGridViewCell cell in dgv.SelectedCells)
                    {
                        sb.AppendFormat("{0}{1}{0},", cell.ValueType == typeof(int) ? "" : "'", cell.Value.ToString());
                    }
                    new frmEditSql() { SqlText = string.Format("delete from {0} where {1} in ({2});", "Table", dgv.CurrentCell.OwningColumn.DataPropertyName, sb.ToString().Trim(',')) }.Show();
                    break;
                case "cmidgv刷新ToolStripMenuItem":
                    dgv.DataSource = DBH.ExecuteDataTable(dgv.Tag.ToString());
                    break;
                case "cmidgv新窗口显示ToolStripMenuItem":
                    ShowInNewWindow(dgv);
                    break;
            }
        }

        /// <summary>
        /// 执行Sql事件
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="frmEditSql"></param>
        private void ExecuteSqlEvent(string sql, Form frmEditSql)
        {
            DataGridView dgv = (DataGridView)frmEditSql.Tag;
            dgv.Tag = sql;
            dgv.DataSource = DBH.ExecuteDataTable(sql);
        }

        /// <summary>
        /// 在新窗口中显示数据表格
        /// </summary>
        /// <param name="dgv"></param>
        private void ShowInNewWindow(DataGridView dgv)
        {
            Form frm = new Form() { StartPosition = FormStartPosition.CenterScreen, Text = dgv.Tag.ToString() };
            frm.Controls.Add(dgv);
            frm.Show();
        }
    }
}
